package nickthissen.iracing.common;

import java.util.ArrayList;

import nickthissen.iracing.common.Task.OnFinishedListener;

public class TaskCollection 
{
	private ArrayList<Task<Void>> tasks;
	private int finishedCount;

	private OnFinishedListener finishedListener;
	
	public TaskCollection()
	{
		tasks = new ArrayList<Task<Void>>();
	}
	
	public void add(Task<Void> task)
	{
		tasks.add(task);
	}
	
	public void setOnFinishedListener(OnFinishedListener listener)
	{
		finishedListener = listener;
	}
	
	private void checkFinished()
	{
		if (finishedCount == tasks.size())
		{
			if (finishedListener != null) finishedListener.finished();
		}
	}
		
	public void executeAll()
	{
		finishedCount = 0;
		for (Task<Void> task : tasks)
		{
			task.setOnFinishedListener(new Task.OnFinishedListener() {
				@Override
				public void finished() 
				{
					finishedCount += 1;
					checkFinished();
				}				
			});
			
			task.execute();
		}
	}
}
